<template>
  <div>
    <div class="table-box" v-if="!childCourseProtableVisible">
      <!-- 必须设置row-key="course_id"，否则拖动后的顺序会出错 -->
      <ProTable
        ref="parentCourseProtable"
        title="用户列表"
        :columns="columns"
        :request-api="getParentCourseTableList"
        :pagination="false"
        @darg-sort="sortParentTable"
        row-key="course_id"
        @row-click="rowClick"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader="scope">
          <el-button type="primary" :icon="CirclePlus" @click="openParentDrawer('新增')"> 新增父级科目 </el-button>
          <el-button type="danger" :icon="Delete" plain :disabled="!scope.isSelected"> 批量删除 </el-button>
        </template>
        <!-- Expand -->
        <template #expand="scope">
          {{ scope.row }}
        </template>
        <!-- usernameHeader -->
        <template #usernameHeader="scope">
          <el-button type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的表头')">
            {{ scope.column.label }}
          </el-button>
        </template>
        <!-- createTime -->
        <template #createTime="scope">
          <el-button type="primary" link @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
            {{ scope.row.createTime }}
          </el-button>
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <el-button type="primary" link :icon="View" @click="openParentDrawer('查看', scope.row)"> 查看 </el-button>
          <el-button type="primary" link :icon="EditPen" @click="openParentDrawer('编辑', scope.row)"> 编辑 </el-button>
          <el-button type="primary" link :icon="Delete" @click="delParentCourse(scope.row)"> 删除 </el-button>
          <el-button type="primary" link :icon="Refresh" @click="openParentDrawer('新增', scope.row)">
            在此题之前插入新科目
          </el-button>
        </template>
      </ProTable>
      <EditCourseDrawer ref="editCourseDrawerRef" />
      <ImportExcel ref="dialogRef" />
    </div>
    <div class="table-box" v-if="childCourseProtableVisible">
      <!-- 必须设置row-key="course_id"，否则拖动后的顺序会出错 -->
      <ProTable
        ref="childCourseProtable"
        title="用户列表"
        :columns="columns"
        :request-api="getChildCourseTableList"
        :pagination="false"
        @darg-sort="sortChildTable"
        row-key="course_id"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader="scope">
          <el-button type="primary" :icon="Back" plain @click="childCourseProtableVisible = false"> 回到父级科目 </el-button>
          <el-button type="primary" :icon="CirclePlus" @click="openChildDrawer('新增')"> 新增子级科目 </el-button>
          <el-button type="danger" :icon="Delete" plain :disabled="!scope.isSelected"> 批量删除 </el-button>
        </template>
        <!-- Expand -->
        <template #expand="scope">
          {{ scope.row }}
        </template>
        <!-- usernameHeader -->
        <template #usernameHeader="scope">
          <el-button type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的表头')">
            {{ scope.column.label }}
          </el-button>
        </template>
        <!-- createTime -->
        <template #createTime="scope">
          <el-button type="primary" link @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
            {{ scope.row.createTime }}
          </el-button>
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <el-button type="primary" link :icon="View" @click="openChildDrawer('查看', scope.row)"> 查看 </el-button>
          <el-button type="primary" link :icon="EditPen" @click="openChildDrawer('编辑', scope.row)"> 编辑 </el-button>
          <el-button type="primary" link :icon="Delete" @click="delChildCourse(scope.row)"> 删除 </el-button>
          <el-button type="primary" link :icon="Refresh" @click="openChildDrawer('新增', scope.row)">
            在此题之前插入新科目
          </el-button>
        </template>
      </ProTable>
      <EditCourseDrawer ref="editCourseDrawerRef" />
      <ImportExcel ref="dialogRef" />
    </div>
  </div>
</template>

<script setup lang="tsx" name="courseManage">
import { ref } from "vue";
import { useRouter } from "vue-router";
import { useHandleData } from "@/hooks/useHandleData";
import { ElMessage } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, View, Refresh, Back } from "@element-plus/icons-vue";
import { addCourseApi, deleteCourseApi, getCourseListApi, sortCourseApi, updateCourseApi } from "@/api/modules/course";
import EditCourseDrawer from "@/views/admin/course_manage/editCourseDrawer.vue";
import { TableColumnCtx } from "element-plus/es/components/table/src/table-column/defaults";
import { Course } from "@/api/interface";

const router = useRouter();
const paths = router.currentRoute.value.path.split("/");
const course_id = paths[paths.length - 1];
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const parentCourseProtable = ref<ProTableInstance>();
const childCourseProtable = ref<ProTableInstance>();
const selectParentCourse = ref<number>(0);
const childCourseProtableVisible = ref<boolean>(false);
const getParentCourseTableList = () => {
  let result = getCourseListApi({ parent_id: 0 });
  return result;
};

const getChildCourseTableList = () => {
  let result = getCourseListApi({ parent_id: selectParentCourse.value });
  return result;
};

// 单击行
const rowClick = (row: any, column: TableColumnCtx<any>) => {
  if (column.property == "radio" || column.property == "operation") return;
  selectParentCourse.value = row.course_id;
  childCourseProtable.value?.getTableList();
  childCourseProtableVisible.value = true;
};

// 表格配置项
const columns: ColumnProps<any>[] = [
  { prop: "order_number", label: "编号", minWidth: 20 },
  { type: "sort", label: "Sort", minWidth: 20 },
  { prop: "title", label: "科目", minWidth: 50 },
  { prop: "introduce", label: "说明", minWidth: 20 },
  { prop: "operation", label: "操作", fixed: "right", minWidth: 20 }
];

const delParentCourse = async (params: any) => {
  await useHandleData(deleteCourseApi, params, `删除题库`);
  parentCourseProtable.value?.getTableList();
};

const delChildCourse = async (params: any) => {
  await useHandleData(deleteCourseApi, params, `删除题库`);
  childCourseProtable.value?.getTableList();
};

// 批量添加用户
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null);

// 打开 drawer(新增、查看、编辑)
const editCourseDrawerRef = ref<InstanceType<typeof EditCourseDrawer> | null>(null);
const openParentDrawer = (title: string, row: Partial<any> = {}) => {
  if (title === "新增") {
    row = { order_number: row.order_number };
  }
  const params = {
    title,
    isView: false,
    row: { ...row },
    api: title === "新增" ? addCourseApi : title === "编辑" ? updateCourseApi : undefined,
    getTableList: parentCourseProtable.value?.getTableList,
    // getTableList: getTableList,
    course_id: course_id,
    order_number: row.order_number ?? "",
    parent_id: 0
  };
  editCourseDrawerRef.value?.acceptParams(params);
};

const openChildDrawer = (title: string, row: Partial<any> = {}) => {
  if (title === "新增") {
    row = { course_id: row.course_id, order_number: row.order_number };
  }
  const params = {
    title,
    isView: false,
    row: { ...row },
    api: title === "新增" ? addCourseApi : title === "编辑" ? updateCourseApi : undefined,
    getTableList: childCourseProtable.value?.getTableList,
    // getTableList: getTableList,
    course_id: course_id,
    order_number: row.order_number ?? "",
    parent_id: selectParentCourse.value
  };
  editCourseDrawerRef.value?.acceptParams(params);
};

// 表格拖拽排序
const sortParentTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  console.log(newIndex, oldIndex);
  const params: { data: { [course_id: number]: number }; course_id: number } = { data: {}, course_id: 0 };
  for (let tableDataIndex in parentCourseProtable.value?.tableData) {
    let course_id = parentCourseProtable.value?.tableData[Number(tableDataIndex)].course_id;
    params.data[Number(course_id)] = Number(tableDataIndex) + 1;
  }
  sortCourseApi(params);
  parentCourseProtable.value?.getTableList();
  ElMessage.success("修改列表排序成功");
};
const sortChildTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  console.log(newIndex, oldIndex);
  const params: { data: { [course_id: number]: number }; course_id: number } = { data: {}, course_id: 0 };
  for (let tableDataIndex in childCourseProtable.value?.tableData) {
    let course_id = childCourseProtable.value?.tableData[Number(tableDataIndex)].course_id;
    params.data[Number(course_id)] = Number(tableDataIndex) + 1;
  }
  sortCourseApi(params);
  childCourseProtable.value?.getTableList();
  ElMessage.success("修改列表排序成功");
};
</script>
